package com.example.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.domain.Machine;
import com.example.service.MachineService;
import com.example.util.api.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/machine")
public class MachineController {

    @Autowired
    private MachineService service;

    @GetMapping("/list")
    public R list(Machine machine) {
        LambdaQueryWrapper<Machine> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(machine.getMachineNumber()), Machine::getMachineNumber, machine.getMachineNumber());
        List<Machine> list = service.list(wrapper);
        return R.data(list);
    }

    @DeleteMapping("/delete")
    public R delete(@RequestParam("machineNumber") String machineNumber) {
        service.removeById(machineNumber);
        return R.success("操作成功");
    }

    @PostMapping("/save")
    public R save(@RequestBody Machine machine) {
        LambdaQueryWrapper<Machine> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Machine::getMachineNumber, machine.getMachineNumber());
        if (service.count(wrapper) > 0) {
            return R.fail("洗衣机编号重复");
        }
        service.save(machine);
        return R.success("操作成功");
    }
    @PutMapping("/update")
    public R update(@RequestBody Machine machine) {
        // 简单的先验证要更新的洗衣机编号是否存在
        LambdaQueryWrapper<Machine> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Machine::getMachineNumber, machine.getMachineNumber());
        if (service.count(wrapper) == 0) {
            return R.fail("要更新的洗衣机不存在");
        }
        boolean result = service.updateMachine(machine);
        if (result) {
            return R.success("更新操作成功");
        }
        return R.fail("更新操作失败");
    }
}
